package com.xmall.member.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmall.define.base.Result;
import com.xmall.define.dto.product.SkuInfoDto;
import com.xmall.member.utils.ConvertUtils;
import com.xmall.member.define.dto.CartDto;
import com.xmall.member.entity.Cart;
import com.xmall.member.mapper.CartMapper;
import com.xmall.member.service.ICartService;
import com.xmall.member.service.remote.ProductServiceFeign;
import com.xmall.utils.XmallUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 购物车 服务实现类
 * </p>
 *
 * @author xmall
 * @since 2023-11-28
 */
@Slf4j
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    @Resource
    private ProductServiceFeign productServiceFeign;

    /**
     * 列表
     */
    @Override
    public List<CartDto> list(Long memberId) {
        List<Cart> cartList = this.list(new QueryWrapper<Cart>().eq("member_id", memberId));
        if(CollectionUtil.isEmpty(cartList)) {
            return new ArrayList<>();
        }
        // 购物车列表
        List<CartDto> cartDtoList = ConvertUtils.CartModule.INSTANCE.toDtoList(this.list(new QueryWrapper<Cart>().eq("member_id", memberId)));
        // 查询商品列表信息
        Result<List<SkuInfoDto>> productListResult = productServiceFeign.list(cartDtoList.stream().map(cartDto -> cartDto.getSkuId()).collect(Collectors.toList()));
        XmallUtils.checkRemoteResult(productListResult);
        Map<Long, SkuInfoDto> skuInfoDtoMap = productListResult.getData().stream().collect(Collectors.toMap(skuInfoDto -> skuInfoDto.getId(), skuInfoDto -> skuInfoDto));
        // 设置商品信息
        cartDtoList.forEach(cartDto -> {
            SkuInfoDto skuInfoDto = skuInfoDtoMap.get(cartDto.getSkuId());
            if(null == skuInfoDto) {
                // 商品是否存在
                cartDto.setExists(false);
            }

            if(null != skuInfoDto) {
                // 设置商品信息
                cartDto.setSkuInfo(skuInfoDto);
                // 商品库存是否充足
                cartDto.setStockEnough(skuInfoDto.getStockNum() - skuInfoDto.getLockedNum() >= cartDto.getQuantity());
            }
        });
        return cartDtoList;
    }

    /**
     * 添加购物车
     */
    @Override
    public void addCart(Long memberId, Long skuId, Integer quantity) {
        Cart cart = this.getOne(new QueryWrapper<Cart>().eq("member_id", memberId).eq("sku_id", skuId));
        if(null == cart) {
            Cart saveCart = new Cart();
            saveCart.setMemberId(memberId);
            saveCart.setSkuId(skuId);
            saveCart.setQuantity(quantity);
            this.save(saveCart);
            return;
        }
        Cart updateCart = new Cart();
        updateCart.setId(cart.getId());
        updateCart.setQuantity(cart.getQuantity() + quantity);
        this.updateById(updateCart);
    }

    /**
     * 更新购物车
     */
    @Override
    public void updateCart(Long id, Integer quantity) {
        if (quantity <= 0) {
            log.error("updateCart: quantity <= 0");
            quantity = 1;
        }
        Cart cart = this.getById(id);
        XmallUtils.notNull(cart);
        Cart updateCart = new Cart();
        updateCart.setId(id);
        updateCart.setQuantity(quantity);
        this.updateById(updateCart);
    }

    /**
     * 删除购物车
     */
    @Override
    public void deleteCart(List<Long> cartIds) {
        this.removeByIds(cartIds);
    }
}
